package com.liu.sms.Listener;

import com.liu.shop.common.constant.RabbitConstant;
import com.liu.shop.common.vo.Email;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;

/**
 * 监听到MQ的消息后发送email
 */


@Component
@Slf4j
public class SendEmail {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String fromUser;

    @RabbitListener(queues = RabbitConstant.EMAIL_QUEUE)
    public void send(Email email, Channel channel, Message message) {
        log.debug("Email:{}", email.toString());
        try{
            // 定义一共邮箱发送者
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            // 将发送者放入help中，
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            // 设置邮箱标题
            helper.setSubject(email.getTitle());
            //true表示开启html扫描
            helper.setText(email.getContent(),true);
            // 收件人
            String[] strArray = {""};
            helper.setTo(email.getToUserList().toArray(strArray)); // 收件人
            // 发件人
            helper.setFrom(fromUser);
            // 发送
            javaMailSender.send(mimeMessage);
            // 自动ack监听到消息后开始发送邮箱
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }catch (Exception e){
            log.error("发送邮件失败", e);
        }
    }
}
